package com.mmallbe.controller.common.interceptor;

import com.github.pagehelper.StringUtil;
import com.google.common.collect.Maps;
import com.mmallbe.common.Const;
import com.mmallbe.common.ResponseCode;
import com.mmallbe.common.ServerResponse;
import com.mmallbe.pojo.User;
import com.mmallbe.util.CookieUtil;
import com.mmallbe.util.JsonUtil;
import com.mmallbe.util.RedisPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {

    //返回值决定是否进入对应的controller
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("--------------preHandle------------------");
        //请求中的Controller 中的方法名
        HandlerMethod handlerMethod = (HandlerMethod)handler;

        //解析HandlerMethod
        String methodName = handlerMethod.getMethod().getName();
        String className = handlerMethod.getBean().getClass().getSimpleName();

        //解析参数，具体的参数key以及value是什么，我们打印日志
        StringBuffer requestParamBuffer = new StringBuffer();
        Map paramMap = request.getParameterMap();
        Iterator it =  paramMap.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry entry = (Map.Entry) it.next();

            String mapKey = (String) entry.getKey();

            String mapValue = StringUtils.EMPTY;

            //request这个参数的map，里面value返回的时一个String[]
            Object obj = entry.getValue();
            if(obj instanceof String[]){
                String[] strs = (String[]) obj;
                mapValue = Arrays.toString(strs);
            }
            requestParamBuffer.append(mapKey).append("=").append(mapValue);

        }

        if(StringUtils.equals(className,"UserManageController") && StringUtils.equals(methodName,"login")){
            log.info("权限拦截器拦截到请求，className：{},methodName:{}",className, methodName);
            //如果拦截到登入请求，不打印参数，因为参数里面有密码，全部会打印到日志中，防止日志泄露
            return true;
        }
        log.info("权限拦截器拦截到请求，className：{},methodName:{},param:{}",className, methodName, paramMap.toString());

        User user = null;

        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isNotEmpty(loginToken)) {
            String userJsonStr = RedisPoolUtil.get(loginToken);
            user = JsonUtil.string2Obj(userJsonStr, User.class);
        }
        if(user ==null || (user.getRole().intValue() != Const.Role.ROLE_ADMIN)){
            //返回false ，即不会调用controller的方法
            response.reset();//这里要添加reset，否则会报异常，getWriter（） has already been
            response.setCharacterEncoding("UTF-8");//geelynote 这里要设置编码，否则会 乱码
            response.setContentType("application/json;charset=UTF-8");//这里设置返回值类型，因为全部是Json接口

            PrintWriter out = response.getWriter();

            if (user == null){
                //上传由于富文本的控件要求，要特殊处理返回值，这里区分是否登入以及是否有权限
                if(StringUtils.equals(className, "ProductManageController") && StringUtils.equals(methodName, "richtextImgUpload")){
                    Map resultMap = Maps.newHashMap();
                    resultMap.put("success",false);
                  resultMap.put("msg","请登录管理员");
                  out.print(JsonUtil.obj2String(resultMap));
                }else{
                    out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("拦截器拦截用户未登录")));
                }
            }else{
                if(StringUtils.equals(className, "ProductManageController") && StringUtils.equals(methodName, "richtextImgUpload")) {
                    Map resultMap = Maps.newHashMap();
                    resultMap.put("success", false);
                    resultMap.put("msg", "无权限操作");
                    out.print(JsonUtil.obj2String(resultMap));
                }else {
                    out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("拦截器拦截用户无权限操作")));
                }
            }
            out.flush();
            out.close();//关闭

            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("--------------postHandle------------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("--------------afterCompletion------------------");
    }
}
